import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken, clearCookies } from '@/utils/cache'
// import { useLayoutStore } from '@/stores'
// 创建axios实例
const service = axios.create({
	baseURL: import.meta.env.VITE_BASE_URL || import.meta.env.BASE_URL || '/',
	timeout: 20 * 1000, // 请求超时时间
})
// 请求拦截器
service.interceptors.request.use(
	config => {
		if (getToken() && !config.headers.Authorization) {
			config.headers.Authorization = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
		}
		if (getToken() && !config.headers['token']) {
			config.headers['token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
		}
		return config
	},
	error => {
		Promise.reject(error)
	},
)
// 响应拦截器
service.interceptors.response.use(
	response => {
		const res = response.data
		const blackList = ['0', '400', '401', '403', '404', '500']
		if (blackList.includes(res.code)) {
			ElMessage({
				message: res.message ? res.message : '服务器繁忙，请稍后再试',
				type: 'warning',
				duration: 5 * 1000,
			})
			return Promise.reject(res)
		} else {
			return res
		}
	},
	error => {
		/* ElMessage({
			message: error.response?.data?.message || error.message,
			type: 'error',
			duration: 5 * 1000,
		}) */
		return Promise.reject(error)
	}
)

export default service
